解構賦值(Destructuring Assignment)是一個在ES6的新特性,用於提取陣列或物件中的資料,解構賦值可以想像是鏡子的概念,將右方的資料往左邊送,然後會一個位置對一個值 (但沒有像鏡子左右顛倒)。
過去陣列內的元素在賦值的時候只能透過底下例子:
let users = ["John", "David","Tina"];
let userA = users[0];
let userB = users[1];
let userC = users[2];
console.log(userA, userB, userC); // John, David, Tina
解構賦值會鏡像的把右邊的資料往左邊送:
let [userA, userB, userC] = ["John", "David","Tina"];
console.log(userA, userB); // John, David, Tina
let users = ["John", "David","Tina"];
let [userA, userB, userC] = users;
console.log(userA, userB, userC); // John, David, Tina
特殊情況:
// 1. 輸入的變數多於右邊的值
let [userA, userB, userC, userD] = ["John", "David","Tina"];
console.log(userA, userB, userC, userD); // John David Tina undefined
// 2. 輸入的變數少於右邊的值
let [userA, userB,, userD] = ["John", "David","Tina","Una"];
console.log(userA, userB, userD); // John David Una
// 3. 解構中有預設值
let [userA, userB, userC = "Jack", userD = "Una"] = ["John", "David","Tina"];
console.log(userA, userB, userC, userD); // John David Tina Una
// 4. String
let str = "一隻小貓";
let [a,b,c,d] = str;
console.log(a,b,c,d); // 一 隻 小 貓
// 5. 交換變數
let a = 123;
let b = 456;
[a,b] = [b,a];
console.log(a,b) // 456 123
與數組不同在於數組是根據索引(index)來對應,而物件是根據屬性名稱來對應。
過去物件只能透過以下例子:
let cat = {
name :"white cat",
color : 'white',
weight: 5
}
let name = cat.name;
let weight = cat.weight;
解構賦值可以非常簡短的達到一樣的效果:
let { name, weight} = cat;
也能重新命名:
let { name : newName, weight} = cat; // newName : white cat